`timescale 1ns / 1ps
/*
 Copyright 2020 Sean Xiao, jxzsxsp@qq.com
 
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at
 
 http://www.apache.org/licenses/LICENSE-2.0
 
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

module exu_BRANCH
(
    input  sys_clk,
    input  rst_n,

    input  i_EXE_vld,
    input  i_BRANCH,
    input  [ 5: 0 ] i_branch_instr, //{rv32i_bgeu,rv32i_bge,rv32i_bltu,rv32i_blt,rv32i_bne,rv32i_beq};

    input  [ 31: 0 ] i_rs1_val,
    input  [ 31: 0 ] i_rs2_val,

    input  [ 31: 0 ] i_PC,
    input  [ 31: 0 ] i_B_imm,
    
    output reg o_B_vld,    // branch valid
    output [ 31: 0 ] o_PC

) ;


wire [ 31: 0 ] op1 = i_rs1_val;
wire [ 31: 0 ] op2 = i_rs2_val;

wire [ 31: 0 ] op_xor = op1 ^ op2;
wire bit_or = |op_xor;

//                             bge                 blt
wire [ 33: 0 ] ext_op1 = ({i_branch_instr[4],i_branch_instr[2]} != 0 ) ? {op1[31],op1[31],op1} : {1'b0,1'b0,op1};
//                             bge                 blt
wire [ 33: 0 ] ext_op2 = ({i_branch_instr[4],i_branch_instr[2]} != 0 ) ? {op2[31],op2[31],op2} : {1'b0,1'b0,op2};
wire [ 33: 0 ] comp_ext_op2 = ~ext_op2 + 1;

wire [ 33: 0 ] op_sub = ext_op1 + comp_ext_op2; //ext_op1 - ext_op2;

assign o_PC = i_PC + i_B_imm;

//assign o_branch_instr = { rv32i_bgtu, rv32i_bgt, rv32i_bltu, rv32i_blt, rv32i_bne, rv32i_beq };
always @( * )
begin
    o_B_vld <= 1'b0;

    if ( i_EXE_vld & i_BRANCH )
    begin
        case ( i_branch_instr )
        6'b00_0001:
        begin //eq
            if ( !bit_or )
                o_B_vld <= 1'b1;
        end
        6'b00_0010:
        begin //bne
            if ( bit_or )
                o_B_vld <= 1'b1;
        end
        6'b00_0100:
        begin //blt
            if ( op_sub[ 33 ] )
                o_B_vld <= 1'b1;
        end
        6'b00_1000:
        begin //bltu
            if ( op_sub[ 33 ] )
                o_B_vld <= 1'b1;
        end
        6'b01_0000:
        begin //bge
            if ( !op_sub[ 33 ] )
                o_B_vld <= 1'b1;
        end
        6'b10_0000:
        begin //bgeu
            if ( !op_sub[ 33 ] )
                o_B_vld <= 1'b1;
        end
        default: ;
        endcase
    end
end

endmodule
